<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Plus, Search } from '@element-plus/icons-vue';
import { ElMessage, ElLoading, UploadProps, UploadFile } from 'element-plus';
import router from '@/router';
import UserUtil from '@/utils/User/User.js';
import { RoadHazardApi } from '@/api/new/RoadHazardApi';
import { TravelNoteApi } from '@/api/new/travelNoteApi.js';

// 灾害信息
const disasterInfo = ref('');
// 灾害类型
const disasterType = ref('');

// 灾害类型映射表
const hazardTypeMap = {
  'landslid': '山体滑坡',
  'roadflooding': '内涝',
  'waterbody': '水体',
  'road_collapse': '路面塌陷',
  'road_frozing': '路面结冰'
};

// 灾害类型选项
const hazardTypeOptions = [
  { value: 'landslid', label: '山体滑坡' },
  { value: 'roadflooding', label: '内涝' },
  { value: 'waterbody', label: '水体' },
  { value: 'road_collapse', label: '路面塌陷' },
  { value: 'road_frozing', label: '路面结冰' }
];

// 上传模式：simple-仅上传，recognition-上传并识别
const uploadMode = ref('recognition');

// 图片上传
interface UploadFileWithUrl extends UploadFile {
  responseUrl?: string;
}
const fileList = ref<UploadFileWithUrl[]>([]);
const uploadedUrls = ref<string[]>([]);
const uploading = ref(false);
const progressPercent = ref(0);

// 地图相关
const mapConfig = reactive({
  zoom: 15,
  zooms: [3, 20],
  center: [116.397428, 39.90923], // 默认北京
});

// 地图标记
const locationMarker = reactive({
  position: [116.397428, 39.90923],
  visible: false,
});

// 地图实例
let mapInstance = null;
let AMapSearch = null; // 搜索服务

// 搜索相关
const searchKeyword = ref('');
const searching = ref(false);
const searchResults = ref([]);

// 选择的位置
const selectedPosition = ref<{ lng: number; lat: number } | null>(null);
const selectedAddress = ref('');

// 处理地图初始化
const handleMapInit = (map) => {
  console.log('地图初始化成功');
  mapInstance = map;

  // 初始化搜索服务
  if (window.AMap && window.AMap.service) {
    AMapSearch = new window.AMap.service.PlaceSearch({
      pageSize: 10,
      pageIndex: 1,
    });
  }

  // 尝试获取当前位置
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { longitude, latitude } = position.coords;
        mapConfig.center = [longitude, latitude];
        if (mapInstance) {
          mapInstance.setCenter([longitude, latitude]);
        }
      },
      (error) => {
        console.error('获取位置失败:', error);
      }
    );
  }
};

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词');
    return;
  }

  searching.value = true;
  searchResults.value = [];

  if (AMapSearch) {
    AMapSearch.search(searchKeyword.value, (status, result) => {
      searching.value = false;

      if (status === 'complete' && result.info === 'OK') {
        searchResults.value = result.poiList.pois || [];
      } else {
        ElMessage.warning('搜索结果为空，请尝试其他关键词');
      }
    });
  } else if (window.AMap && window.AMap.plugin) {
    // 如果没有初始化搜索服务，尝试使用插件方式
    window.AMap.plugin('AMap.PlaceSearch', () => {
      const placeSearch = new window.AMap.PlaceSearch({
        pageSize: 10,
        pageIndex: 1,
      });

      placeSearch.search(searchKeyword.value, (status, result) => {
        searching.value = false;

        if (status === 'complete' && result.info === 'OK') {
          searchResults.value = result.poiList.pois || [];
        } else {
          ElMessage.warning('搜索结果为空，请尝试其他关键词');
        }
      });
    });
  } else {
    searching.value = false;
    ElMessage.error('搜索服务初始化失败');
  }
};

// 选择搜索结果
const handleSelectSearchResult = (item) => {
  if (item && item.location) {
    const { lng, lat } = item.location;

    console.log(`设置标记位置: [${lng}, ${lat}]`);

    // 更新选择的位置
    selectedPosition.value = { lng, lat };

    // 更新标记位置
    locationMarker.position = [lng, lat];
    locationMarker.visible = true;

    // 更新地址文本
    selectedAddress.value = item.address || item.name || `位置坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}`;

    // 更新地图中心
    mapConfig.center = [lng, lat];

    // 确保地图中心移动到选择的位置
    if (mapInstance) {
      mapInstance.setCenter([lng, lat]);
    }

    // 清空搜索结果
    searchResults.value = [];

    console.log('更新后的标记状态:', {
      position: locationMarker.position,
      visible: locationMarker.visible,
      selectedAddress: selectedAddress.value
    });
  }
};

// 处理地图点击
const handleMapClick = (e) => {
  console.log('地图点击事件:', e);

  const { lng, lat } = e.lnglat;
  selectedPosition.value = { lng, lat };
  locationMarker.position = [lng, lat];
  locationMarker.visible = true;

  // 这里应该调用高德地图API进行逆地理编码
  // 由于没有实际API，这里使用模拟数据
  selectedAddress.value = `位置坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}`;

  // 清空搜索结果
  searchResults.value = [];
};

// 清除选择的位置
const clearLocation = () => {
  selectedPosition.value = null;
  selectedAddress.value = '';
  locationMarker.visible = false;
};

// 处理文件变更
const handleFileChange = async (uploadFile) => {
  if (!beforeUpload(uploadFile.raw)) {
    return;
  }

  uploading.value = true;
  progressPercent.value = 0;

  try {
    let imageUrl;

    // 根据上传模式选择不同的上传方法
    if (uploadMode.value === 'recognition') {
      // 使用识别接口上传图片
      const result = await TravelNoteApi.uploadImageForRecognition(uploadFile.raw);
      console.log('图片识别结果:', result);

      // 提取图片URL和灾害类型
      imageUrl = result.image;
      const hazardTypes = result.hazard_name || [];

      // 若为空则提示无识别
      if(!result.hazard_name){
        ElMessage.error('未识别到灾害，请自行选择灾害类型');
      }

      // 如果有识别结果，自动填充灾害类型
      if (hazardTypes.length > 0) {
        // 获取置信度最高的灾害类型
        const topHazard = hazardTypes.sort((a, b) => b.confidence - a.confidence)[0];
        const confidence = Math.round(topHazard.confidence * 100);

        // 自动选择灾害类型
        disasterType.value = topHazard.class;

        // 如果灾害信息为空，则自动填充
        if (!disasterInfo.value) {
          const hazardName = hazardTypeMap[topHazard.class] || topHazard.class;
          disasterInfo.value = `系统检测到可能的${hazardName}(置信度:${confidence}%)，请补充详细信息。`;
        }

        // 显示识别结果提示
        const hazardName = hazardTypeMap[topHazard.class] || topHazard.class;
        ElMessage.success(`图片上传成功，系统识别为${hazardName}(置信度:${confidence}%)`);
      } else {
        ElMessage.success('图片上传成功');
      }
    } else {
      // 使用普通上传接口
      imageUrl = await TravelNoteApi.uploadImage(uploadFile.raw);
      ElMessage.success('图片上传成功');
    }

    // 更新文件状态
    uploadFile.status = 'success';
    uploadFile.responseUrl = imageUrl;

    // 添加到已上传URL列表
    uploadedUrls.value.push(imageUrl);

    console.log('上传成功，图片URL:', imageUrl);
    console.log('当前已上传图片列表:', uploadedUrls.value);

    uploading.value = false;
    progressPercent.value = 100;
  } catch (error) {
    console.error('上传图片失败:', error);

    // 更新文件状态
    uploadFile.status = 'fail';

    ElMessage.error(`上传失败: ${error.message || '未知错误'}`);
    uploading.value = false;
  }
};

// 处理上传进度
const handleProgress: UploadProps['onProgress'] = (event) => {
  progressPercent.value = Math.floor(event.percent);
};

// 文件移除处理
const handleRemove: UploadProps["onRemove"] = (file) => {
  uploadedUrls.value = uploadedUrls.value.filter(url => url !== (file as UploadFileWithUrl).responseUrl);
  console.log('移除图片后的列表:', uploadedUrls.value);
};

// 文件类型和大小验证
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png', 'image/webp'].includes(rawFile.type)) {
    ElMessage.error('仅支持 JPG/PNG/WEBP 格式');
    return false;
  }
  if (rawFile.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB');
    return false;
  }
  return true;
};

// 超出限制处理
const handleExceed = () => {
  ElMessage.warning('只能上传1张灾害图片');
};

// 表单验证
const validateForm = () => {
  const errors = [];
  if (!disasterInfo.value.trim()) errors.push('请填写灾害信息');
  if (!disasterType.value) errors.push('请选择灾害类型');
  if (!selectedPosition.value) errors.push('请选择灾害位置');
  if (uploadedUrls.value.length < 1) errors.push('请上传灾害图片');

  if (errors.length > 0) {
    ElMessage.warning(errors.join('，'));
    return false;
  }
  return true;
};

// 发布灾害信息
const publishDisaster = async () => {
  // 表单验证
  if (!validateForm()) return;

  // 使用UserUtil.isLogin()检查登录状态
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录');
    return;
  }

  // 使用UserUtil.getUserId()获取用户ID
  const userId = UserUtil.getUserId();
  if (!userId) {
    ElMessage.warning('无法获取用户信息，请重新登录');
    return;
  }

  const loading = ElLoading.service({
    lock: true,
    text: '正在发布灾害信息...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    // 准备发布参数
    const params = {
      disasterInfo: disasterInfo.value,
      disasterType: disasterType.value,
      userID: userId,
      latitude: selectedPosition.value.lat,
      longitude: selectedPosition.value.lng,
      videoUrl: uploadedUrls.value.join(',') // 将图片URL数组转为逗号分隔的字符串
    };

    console.log('发布灾害信息参数:', params);

    // 调用RoadHazardApi.publishDisaster发布灾害信息
    const result = await RoadHazardApi.publishDisaster(
      params.disasterInfo,
      params.disasterType,
      params.userID,
      params.latitude,
      params.longitude,
      params.videoUrl,
      params.disasterType
    );

    console.log('发布灾害信息结果:', result);

    loading.close();
    ElMessage.success('灾害信息发布成功');

    // 重置表单
    resetForm();

    router.go(0);
  } catch (error) {
    console.error('发布灾害信息失败:', error);
    loading.close();
    ElMessage.error(`发布失败: ${error.message || '未知错误'}`);
  }
};

// 重置表单
const resetForm = () => {
  disasterInfo.value = '';
  disasterType.value = '';
  fileList.value = [];
  uploadedUrls.value = [];
  selectedPosition.value = null;
  selectedAddress.value = '';
  locationMarker.visible = false;
};

// 获取当前位置
onMounted(() => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { longitude, latitude } = position.coords;
        mapConfig.center = [longitude, latitude];
      },
      (error) => {
        console.error('获取位置失败:', error);
      }
    );
  }
});
</script>

<template>
  <div class="container">
    <div class="push-container">
      <div class="header">
        <span class="header-icon"></span>
        <span class="header-title">发布灾害信息</span>
      </div>

      <!-- 灾害图片上传 -->
      <div class="img-list">
        <div class="section-title">灾害图片 <span class="required">*</span></div>

        <!-- 上传模式切换 -->
        <div class="upload-mode-switch">
          <el-radio-group v-model="uploadMode" size="small">
            <el-radio-button label="recognition">上传并识别</el-radio-button>
            <el-radio-button label="simple">仅上传图片</el-radio-button>
          </el-radio-group>
          <div class="upload-tip">
            {{ uploadMode === 'recognition' ? '系统将自动识别灾害类型' : '仅上传图片，不进行识别' }}
          </div>
        </div>

        <el-upload
          v-model:file-list="fileList"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-remove="handleRemove"
          :limit="1"
          :before-upload="beforeUpload"
          accept="image/*"
          :on-exceed="handleExceed"
          :on-progress="handleProgress"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="upload-progress" v-if="uploading">
              <el-progress
                :percentage="progressPercent"
                :stroke-width="16"
                :format="(percent) => `${percent}%`"
              />
            </div>
          </template>
        </el-upload>
      </div>

      <el-divider style="margin: 12px 0" />

      <!-- 灾害信息部分 -->
      <div class="disaster-info">
        <!-- 灾害类型选择 -->
        <div class="form-item">
          <div class="label">灾害类型 <span class="required">*</span></div>
          <el-select
            v-model="disasterType"
            placeholder="请选择灾害类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in hazardTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 灾害信息 -->
        <div class="form-item">
          <div class="label">灾害信息 <span class="required">*</span></div>
          <el-input
            v-model="disasterInfo"
            type="textarea"
            :rows="5"
            maxlength="500"
            show-word-limit
            placeholder="请详细描述灾害情况、影响范围、人员伤亡等信息"
          />
        </div>

        <!-- 灾害位置 -->
        <div class="form-item">
          <div class="label">灾害位置 <span class="required">*</span></div>
          <div class="map-wrapper">
            <div class="search-box-wrapper">
              <el-input
                v-model="searchKeyword"
                placeholder="输入地址搜索"
                :disabled="searching"
                @keyup.enter="handleSearch"
              >
                <template #append>
                  <el-button :icon="Search" @click="handleSearch" :loading="searching">
                    搜索
                  </el-button>
                </template>
              </el-input>
              <div v-if="searchResults.length > 0" class="search-results">
                <div
                  v-for="(item, index) in searchResults"
                  :key="index"
                  class="search-result-item"
                  @click="handleSelectSearchResult(item)"
                >
                  <span class="result-name">{{ item.name }}</span>
                  <span class="result-address">{{ item.address || item.district }}</span>
                </div>
              </div>
            </div>

            <el-amap
              class="amap-box"
              :zoom="mapConfig.zoom"
              :zooms="mapConfig.zooms"
              :center="mapConfig.center"
              @init="handleMapInit"
              @click="handleMapClick"
            >
              <!-- 标记 -->
              <el-amap-marker
                :position="locationMarker.position"
                :visible="locationMarker.visible"
              />
            </el-amap>

            <div v-if="selectedPosition && locationMarker.visible" class="selected-location">
              <el-tag>已选择位置: {{ selectedAddress }}</el-tag>
              <el-button type="primary" link @click="clearLocation">清除</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="submit">
        <button class="publishBtn" @click="publishDisaster">
          <span class="btn-content">发布</span>
        </button>
        <button class="clearBtn" @click="resetForm">
          <span class="btn-content">重置</span>
        </button>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.container {
  flex: 1;
  padding: 0 24px;
  width: 67%;
  max-width: 900px;
  margin: 0 auto;

  .push-container {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .header {
      padding: 16px 20px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      align-items: center;

      .header-icon {
        width: 4px;
        height: 16px;
        background-color: #ff2442;
        margin-right: 8px;
        border-radius: 2px;
      }

      .header-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }
    }

    .img-list {
      padding: 20px;

      .section-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;

        .required {
          color: #ff2442;
          margin-left: 4px;
        }
      }

      .upload-mode-switch {
        margin-bottom: 16px;

        .upload-tip {
          font-size: 12px;
          color: #999;
          margin-top: 8px;
        }
      }

      .upload-tip {
        font-size: 14px;
        color: #999;
        margin-bottom: 12px;
      }
    }

    .disaster-info {
      padding: 0 20px 20px;

      .form-item {
        margin-bottom: 24px;

        .label {
          font-size: 14px;
          font-weight: 500;
          margin-bottom: 8px;
          color: #333;

          .required {
            color: #ff2442;
            margin-left: 4px;
          }
        }
      }
    }

    .search-box-wrapper {
      position: relative;
      margin-bottom: 10px;
      z-index: 1000;

      .search-results {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: white;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        max-height: 300px;
        overflow-y: auto;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

        .search-result-item {
          padding: 10px 15px;
          cursor: pointer;
          border-bottom: 1px solid #f0f0f0;

          &:hover {
            background-color: #f5f7fa;
          }

          &:last-child {
            border-bottom: none;
          }

          .result-name {
            display: block;
            font-weight: bold;
            margin-bottom: 3px;
          }

          .result-address {
            display: block;
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }

    .map-wrapper {
      width: 100%;
      margin-bottom: 24px;

      .amap-box {
        width: 100%;
        height: 400px;
        margin-bottom: 10px;
      }

      .selected-location {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-top: 8px;
        margin-bottom: 16px;
      }
    }

    .submit {
      padding: 0 20px 24px;
      display: flex;
      justify-content: center;
      gap: 16px;
      margin-top: 16px;

      button {
        width: 120px;
        height: 40px;
        font-size: 16px;
        border-radius: 20px;
        border: none;
        cursor: pointer;
        transition: all 0.3s;
      }

      .publishBtn {
        background-color: #ff2442;
        color: #fff;

        &:hover {
          background-color: #ff3a58;
        }
      }

      .clearBtn {
        background-color: #f5f5f5;
        color: #666;
        border: 1px solid #ddd;

        &:hover {
          background-color: #eee;
        }
      }
    }
  }
}

.upload-progress {
  margin-top: 10px;
  width: 80%;
}

/* 确保地图容器有明确的高度 */
:deep(.amap-container) {
  height: 400px !important;
  width: 100% !important;
}

/* 自定义上传框大小 */
:deep(.el-upload--picture-card) {
  width: 240px;
  height: 240px;
  line-height: 240px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 240px;
  height: 240px;
}

/* 修改上传图标大小，但保持搜索图标原始大小 */
:deep(.el-upload .el-icon) {
  font-size: 28px;
}

/* 恢复搜索按钮图标大小 */
:deep(.el-input-group__append .el-icon),
:deep(.el-button .el-icon) {
  font-size: 16px;
}
</style>
